var tree;
var tabIndex = '0';
var accessToken;
var g_domId;
var g_url;
var g_code;
var btnStatus = '1'; //1：直播 2：本地录像
$(document).ready(function () {
  getCameraList();
  getYsyToken();
});

function getCameraList() {
  AjaxRequest('/device/list/all', callBack);

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;
      var data1 = [];
      var data2 = [];
      $.each(data, function (i, e) {
        if (e.type == 3) {
          data1.push({
            title: e.name,
            code: e.code,
            type: e.type,
            id: e.id,
          });
        } else if (e.type == 2) {
          data2.push({
            title: e.name,
            code: e.code,
            type: e.type,
            id: e.id,
          });
        }
      });
      initTree(data1, data2);
    }
  }
}

function initTree(data1, data2) {
  layui.use('tree', function () {
    tree = layui.tree;

    //渲染
    tree.render({
      elem: '#tree',
      data: [
        {
          title: '水渠视频监控',
          children: data1,
          spread: true,
        },
        {
          title: '水源地水质监测',
          children: data2,
        },
      ],
      id: 'tree',
      click: function (obj) {
        var children = obj.data.children;

        if (!children) {
          var code = obj.data.code;
          var type = obj.data.type;
          var id = obj.data.id;
          if (type == '3') {
            getAlarmList(type, code);
          } else {
            getAlarmList(type, id);
          }

          $('#switch-btn').text('回放');
          btnStatus = '1';

          treeClick(code);
        }
      },
    });

    if (data1.length > 0) {
      getAlarmList(3, data1[0].code);
      treeClick(data1[0].code);
    }
  });
}

function treeClick(code) {
  var childNodes = $('#tab-' + tabIndex)[0].children.length;
  const timestamp = new Date().getTime();
  var str = ``;
  switch (
    tabIndex //tabIndex:0-1画面 1-4画面 2-8画面 3-16画面
  ) {
    case '0':
      if (childNodes > 0) {
        $('#tab-' + tabIndex)
          .children()
          .eq(0)
          .remove();
      }
      str = ` <div class="tab${tabIndex}-item" id="id${timestamp}" style="height: calc(100% - 2px)">
              </div>`;
      g_domId = 'id' + timestamp;
      g_code = code;
      break;
    case '1':
      if (childNodes > 3) {
        $('#tab-' + tabIndex)
          .children()
          .eq(0)
          .remove();
      }
      str = ` <div class="tab${tabIndex}-item" id="id${timestamp}" style="height: calc(50% - 2px)">
              </div>`;
      break;
    case '2':
      if (childNodes > 7) {
        $('#tab-' + tabIndex)
          .children()
          .eq(0)
          .remove();
      }
      str = ` <div class="tab${tabIndex}-item" id="id${timestamp}" style="height: calc(50% - 2px)">
              </div>`;
      break;
    case '3':
      if (childNodes > 15) {
        $('#tab-' + tabIndex)
          .children()
          .eq(0)
          .remove();
      }
      str = ` <div class="tab${tabIndex}-item" id="id${timestamp}" style="height: calc(25% - 2px)">
              </div>`;
      break;
  }

  $('#tab-' + tabIndex).append(str);
  setTimeout(() => {
    getCameraAddress('id' + timestamp, code);
  }, 200);
}

function getAlarmList(type, code) {
  var renderPage = function (curr) {
    var url;
    if (type == 3) {
      url = '/alarm/list?code=' + code + '&pageNum=' + curr + '&pageSize=2';
    } else {
      url = '/alarm/list?linkId=' + code + '&pageNum=' + curr + '&pageSize=2';
    }
    AjaxRequest(url, callBack);

    function callBack(result) {
      if (result.status == 200) {
        var str = '';
        var data = result.result.data;
        if (data.length > 0) {
          var pageData = {
            count: result.result.total,
            limit: 2,
            curr: curr || 1,
          };
          $.each(data, function (i, e) {
            str += `<div class="info-item">
                      <div class="info-title">告警信息</div>
                      <div class="info-content">
                        <div onclick="showPhotoWindow('${e.alarmTime}','${e.alarmImage}')" class="layer-photos-demo">
                          <img src="/images/${e.alarmImage}">
                        </div>
                        <div class="detail-info">
                          <div>时间：${e.alarmTime}</div>
                          <div>设备地址：${e.deviceName}</div>
                          <div>告警类型：${e.eventTypeDesc}</div>
                        </div>
                      </div>
                    </div>`;
          });
          $('#info-list').empty().append(str);

          layui.laypage.render({
            elem: 'page',
            count: pageData.count,
            limit: pageData.limit,
            curr: pageData.curr,
            jump: function (obj, first) {
              // 当不是第一页，且用户有点击分页的操作，则重新渲染内容
              if (!first) {
                renderPage(obj.curr);
              }
            },
            layout: ['page'],
          });
        }
      }
    }
  };

  // 初始化渲染第一页
  renderPage(1);
}

function getCameraAddress(domId, code) {
  AjaxRequest(
    '/data/device/ys/live/address/get',
    callBack,
    {
      code: code,
      protocol: 1,
      type: tabIndex == '0' ? btnStatus : '1', //1-预览，2-本地录像回放，3-云存储录像回放，非必选，默认为1；回放仅支持rtmp、ezopen、flv协议
      // type: '2',
    },
    'post'
  );
  function callBack(result) {
    if (result.status == 200) {
      if (tabIndex == '0') {
        g_url = result.result;
      }
      if (tabIndex == '0') {
        initVideo(domId, result.result, btnStatus == '1' ? 'pcLive' : 'pcRec');
      } else {
        initVideo(domId, result.result, 'pcLive');
      }
    }
  }
}

function initVideo(domId, url, template) {
  new EZUIKit.EZUIKitPlayer({
    id: domId, // 视频容器ID
    accessToken: accessToken,
    url: url,
    template: template, // simple - 极简版;standard-标准版;security - 安防版(预览回放);voice-语音版; theme-可配置主题；
    // plugin: ['talk'], // 加载插件，talk-对讲
    // width: 600,
    // height: 400,
  });
}

function getYsyToken() {
  AjaxRequest('/data/device/ys/token/get', callBack, {}, 'post');
  function callBack(result) {
    if (result.status == 200) {
      accessToken = result.result;
    }
  }
}

$('.tab-item').click(function (e) {
  $(e.currentTarget).addClass('active').siblings().removeClass('active');
  tabIndex = $(this)[0].dataset.index;
  $('.tab-content').hide();
  $('#switch-btn').hide();
  switch (tabIndex) {
    case '0':
      $('#tab-0').show();
      $('#switch-btn').show();
      break;
    case '1':
      $('#tab-1').show();
      break;
    case '2':
      $('#tab-2').show();
      break;
    case '3':
      $('#tab-3').show();
      break;
  }
});

// 直播、录像切换
function switchVideo() {
  if (btnStatus == '1') {
    $('#switch-btn').text('直播');
    btnStatus = '2';
    getCameraAddress(g_domId, g_code);
    // initVideo(g_domId, g_url, 'pcRec');
  } else {
    $('#switch-btn').text('回放');
    btnStatus = '1';
    initVideo(g_domId, g_url, 'pcLive');
  }
}
